package com.qiangesoft.pay.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.qiangesoft.pay.app.config.WxPayProperties;
import com.qiangesoft.pay.app.service.IRefundService;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class RefundServiceImpl implements IRefundService {

    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private RefundService refundService;

    @Override
    public void refund(String outTradeNo, String outRefundNo, String refundReason, Long totalFee, Long refundFee) {
        if (StrUtil.isBlank(outTradeNo)) {
            throw new RuntimeException("商户交易号不能为空");
        }
        if (StrUtil.isBlank(outRefundNo)) {
            throw new RuntimeException("商户退款号不能为空");
        }
        if (StrUtil.isBlank(refundReason)) {
            throw new RuntimeException("退款原因不能为空");
        }
        if (totalFee == null || totalFee <= 0) {
            throw new RuntimeException("交易金额必须大于0");
        }
        if (refundFee == null || refundFee <= 0) {
            throw new RuntimeException("退款金额必须大于0");
        }
        if (totalFee < refundFee) {
            throw new RuntimeException("退款金额不能大于支付总金额");
        }

        // todo 退款记录

        CreateRequest request = new CreateRequest();
        request.setOutTradeNo(outTradeNo);
        request.setOutRefundNo(outRefundNo);
        request.setReason(refundReason);
        request.setNotifyUrl(wxPayProperties.getRefundNotifyUrl());
        AmountReq amount = new AmountReq();
        amount.setTotal(totalFee);
        amount.setRefund(refundFee);
        amount.setCurrency("CNY");
        request.setAmount(amount);
        // 此处返回值不代表真实退款情况，仅微信对此申请受理结果
        refundService.create(request);
    }

    @Override
    public Refund query(String outRefundNo) {
        QueryByOutRefundNoRequest request = new QueryByOutRefundNoRequest();
        request.setOutRefundNo(outRefundNo);
        return refundService.queryByOutRefundNo(request);
    }

    @Override
    public void notify(Refund refund) {
        Status status = refund.getStatus();
        if (Status.SUCCESS.equals(status)) {
            String successTime = refund.getSuccessTime();
            if (StrUtil.isNotBlank(successTime)) {
                DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
                OffsetDateTime offsetDateTime = OffsetDateTime.parse(successTime, formatter);
                LocalDateTime refundTime = offsetDateTime.toLocalDateTime();
            }
            // todo 退款成功

        }
    }

}
